﻿#include <windows.h>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib")

int main()
{
    // 0. 初始化网络环境
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
    {
        printf("初始化Winsock失败\n");
        return -1;
    }
    printf("初始化Winsock成功\n");


    // 1. 创建客户端句柄（套接字）
    // AF_INET ipv4
    // SOCK_STREAM --> TCP       SOCK_DREAM --> UDP
    SOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0);

    if (INVALID_SOCKET == sockClient)
    {
        printf("创建客户端句柄失败\n");

        return -1;
    }
    printf("1. 创建客户端句柄成功\n");
    // 2. 连接服务端端口号和IP地址

    SOCKADDR_IN addr = {};
    addr.sin_family = AF_INET;
    addr.sin_port = htons(50000);
    addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); // IP地址
    int ret = connect(sockClient, (sockaddr*)&addr, sizeof(SOCKADDR_IN));

    if (SOCKET_ERROR == ret)
    {
        printf("连接服务端失败\n");
        return -1;
    }
    while (1)
    {

        char buf[1024] = { 0 };
        printf("请输入字符：");
        //从控制台一次读取一行
        gets_s(buf);

        // 3.发生数据给服务端

        int retSend = send(sockClient, buf, strlen(buf), 0);
        // retSend !=13 发送失败
        // 4.接受服务端数据

        char szRecv[4096] = {};
        int retRecv = recv(sockClient, szRecv, 4096, 0);
        if (retRecv <= 0)
        {
            printf("接受服务端数据失败\n");
            return -1;
        }
        printf("接受到服务端数据：%s\n", szRecv);

    }
    // 5.关闭客户端句柄
    closesocket(sockClient);


    return 0;
}